# coding: utf-8

from gtts import gTTS
import io
import pygame

class SoundInfo():
    def __init__(self):
        pygame.init()
        pygame.mixer.init()
    
    def __del__(self):  
        pygame.mixer.quit()
        pygame.quit()
        
    def play_text(self, text: str) -> bool:
        
            if not text:
                return False

            if all('\u4e00' <= char <= '\u9fff' for char in text):
                language = "zh-CN"
            elif all(char.isalpha() for char in text.replace(" ", "")):
                language = "en"
            else:
                print("Error: The text contains invalid characters.")
                return False

            try:
                tts = gTTS(text=text, lang=language, slow=False)
                audio_data = io.BytesIO()
                tts.write_to_fp(audio_data)

                audio_data.seek(0)
                sound = pygame.mixer.Sound(audio_data)

                # 创建一个通道播放音频
                channel = pygame.mixer.find_channel(True)
                if channel is None:
                    print("Error: No available channels to play the audio.")
                    return False

                channel.play(sound)

                # 等待音频播放完毕
                while pygame.mixer.get_busy():
                    pygame.time.Clock().tick(10)

                return True
            
            except (AttributeError, IOError, ValueError) as e:
                print(f"Error occurred while creating or loading the audio: {e}")
                return False
            finally:
                audio_data.close()
            
if __name__ == "__main__":
    
    sound = SoundInfo()
    sound.play_text("宇美大傻子")
    sound.play_text("Yumei is a genius")